<template>
  <view class="container">
    <u-navbar
      :is-fixed="false"
      :border-bottom="false"
      :is-back="false"
      title="购物车"
      :background="{ background: '#fff' }"
      title-color="#000"
    >
    </u-navbar>
		<u-toast ref="uToast" />
    <u-calendar :z-index="9999999" :min-date="min" :max-date="max" v-model="showC" :mode="'date'" @change="cT"></u-calendar>
    <u-popup v-model="showLocation" mode="bottom" border-radius="14">
      <view class="popup people">
        <view style="font-weight: bold;margin-bottom: 20rpx;" @click="clickCT">{{receivetime}}</view>
        <view style="font-weight: bold;margin-bottom: 20rpx;">选择地址</view>
        <view @click="curPIndex = pIndex" class="each" :class="{eachChoose: curPIndex == pIndex}" v-for="(p, pIndex) in locations" :key="pIndex">
          <view class="name">姓名：{{p.name}}</view>
          <view class="cardno">电话：{{p.phone}}</view>
          <view class="cardno">地址：{{p.address}}</view>
        </view>
        <view class="btn2" @click="addOrder">提交</view>
      </view>
		</u-popup>
    <view class="cart-scroll">
      <u-swipe-action
        :show="item.show"
        :index="index"
        v-for="(item, index) in cartList"
        :key="item.id"
        @click="click(item)"
        :options="options"
      >
        <view class="item u-border-bottom each-good" style="position: relative">
          <u-checkbox
            @change="checkboxChange($event, index, item)"
            v-model="item.check"
          ></u-checkbox>
          <image @click="articleDetail(item)" mode="aspectFill" :src="item.goodsImg" />
          <view @click="articleDetail(item)" class="title-wrap">
            <text class="title u-line-2">{{ item.goodsName }}</text>
            <text class="title u-line-2">¥{{ item.goodsPrice }}</text>
          </view>
          <u-number-box
            class="number"
            v-model="item.cnt"
            @change="valChange(item)"
          ></u-number-box>
        </view>
      </u-swipe-action>
    </view>
		<u-empty v-if="!userInfo.id || cartList.length == 0" :text="emptyText" mode="list"></u-empty>

    <view class="pay" v-if="cartList.length">
      <view class="flex-center">
        <u-checkbox @change="checkboxChangeAll($event)" v-model="allCheck"
          >全选</u-checkbox
        >
        <view class="red" @click="clearCart()">清空购物车</view>
      </view>
      <view>
        <!-- <text style="font-size: 24rpx;">合计</text>
        <text style="font-size: 24rpx;">¥</text>
        <text style="font-size: 30rpx;">{{ totalPrice }}</text> -->
        <text class="btn" @click="jiesuan">结算</text>
      </view>
    </view>
  </view>
</template>

<script>
import moment from 'moment';
import { getCarts, deleteCart, addOrder } from "../../api/system/api";
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          title:
            "长安回望绣成堆，山顶千门次第开，一骑红尘妃子笑，无人知是荔枝来",
          images: "https://cdn.uviewui.com/uview/common/logo.png",
          show: false,
          check: true,
        },
      ],
      receivetime: '请选择取衣日期',
      showC: false,
      min: moment().format('YYYY-MM-DD'),
      max: moment().add(30, 'days').format('YYYY-MM-DD'),
      allCheck: true,
      options: [
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        },
      ],
      totalPrice: 0,
      cartList: [],
      userInfo: {},
      emptyText: "请先登录~",
      checkIds: [],
      locations: [],
      showLocation: false,
      curPIndex: null
    };
  },
  onShow() {
    uni.getStorage({
      key: "userInfo",
      success: (res) => {
        this.userInfo = res.data;
        this.locations = this.userInfo.location ? JSON.parse(this.userInfo.location) : []
        this.refreshCarts()
      },
    });
  },
  methods: {
    refreshCarts() {
      getCarts().then(carts => {
        carts = carts.data
        let cart = carts.filter(v => v.userId == this.userInfo.id)
        this.cartList = cart.map(v => {
          return {
            ...v,
            check: true,
            cnt: 1
          }
        });
        console.log(this.cartList)
        if (this.cartList.length == 0) {
          this.emptyText = "购物车是空的~";
        } else {
          this.handlePrice();
        }
      })
    },
    click(item) {
      deleteCart(item.id).then(res => {
        if (res.code == '200') {
          let index = this.checkIds.findIndex(v => v == item.id)
          this.checkIds.splice(index, 1)
          this.$refs.uToast.show({
            title: "移除购物车~",
            type: "success",
          });
          this.refreshCarts()
        }
      })
    },
    checkboxChange(event, index, item) {
      if (event.value) {
        let index = this.checkIds.findIndex(v => v == item.id)
        this.checkIds.splice(index, 1)
      } else {
        this.checkIds.push(item.id)
      }
      this.cartList[index].check = event.value;
      this.allCheck =
        this.cartList.filter((v) => v.check).length == this.cartList.length
          ? true
          : false;
      this.handlePrice()
    },
    checkboxChangeAll(event) {
      if (event.value) {
        this.checkIds = this.cartList.map(v => v.id)
      } else {
        this.checkIds = []
      }
      this.cartList = this.cartList.map((v) => {
        return {
          ...v,
          check: event.value,
        };
      });
      this.$forceUpdate();
      this.handlePrice()
    },
    valChange(item) {
      this.handlePrice()
      this.updateCartStorage()
    },
    handlePrice() {
      this.totalPrice = 0;
      let total = 0;
      let cartList = this.cartList.filter(v => v.check)
      for (let item of cartList) {
        total += item.cnt * Number(item.goodsPrice)
      }
      this.totalPrice = total
    },
    jiesuan() {
      let total = 0;
      let checks = this.cartList.filter(v => v.check)
      if (checks.length == 0) {
        this.$refs.uToast.show({
          title: "请选择服务",
          type: "error",
        });
        return
      }
      for (let item of checks) {
        total += item.cnt
      }
      console.log(total)
      if (total === 0) {
        this.$refs.uToast.show({
          title: "请选择服务数量",
          type: "error",
        });
        return
      }
      let cartList = this.cartList.filter(v => v.check)
      if (cartList.length) {
        // if (this.userInfo.money < this.totalPrice) {
        //   this.$refs.uToast.show({
        //     title: "余额不足，请到个人中心充值~",
        //     type: "error",
        //   });
        //   return
        // }
        // this.receivetime = '请选择取衣日期'
        // this.showLocation = true;
        // 跳转到结算页面
        console.log(cartList)
        this.$u.route("/pages/good/payDetail", {
          goods: JSON.stringify(cartList.map(v => {
            return {
              goodsId: v.goodsId,
              goodsImg: v.goodsImg,
              goodsName: v.goodsName,
              goodsPrice: v.goodsPrice,
              cnt: v.cnt,
            }
          })),
          userId: this.userInfo.id
        });
      } else {
        this.$u.toast(`请选择商品`);
      }
    },
    updateCartStorage() {
      this.cartStorage[this.userInfo.id] = this.cartList
      uni.setStorage({
        key:'cartList',
        data: this.cartStorage,
        success: () => {
          
        }
      })
    },
    cT(e) {
      this.receivetime = e.result;
    },
    clickCT() {
      console.log(111)
      this.showC = true
    },
    addOrder() {
      // 提交订单  清空已勾选的购物车；
      if (this.receivetime == '请选择取衣日期') {
        this.$refs.uToast.show({
          title: "请选择取衣日期",
          type: "error",
        });
        return
      }
      if (this.totalPrice == 0) {
        this.$refs.uToast.show({
          title: "请选择商品",
          type: "error",
        });
        return
      }
      if (this.curPIndex === null) {
        this.$refs.uToast.show({
          title: "请选择地址",
          type: "error",
        });
        return
      }
      // 刷新购物车
      let l = this.locations[this.curPIndex]
      let goodsinfo = this.cartList.filter(v => v.check).map(v => {
        return {
          cnt: v.cnt,
          name: v.goodsName,
          img: v.goodsImg
        }
      })
      addOrder({
        userId: this.userInfo.id,
        status: '已付款',
        location: `${l.name}-${l.phone}-${l.address}`,
        price: this.totalPrice,
        goodsinfo: JSON.stringify(goodsinfo),
        orderNo: `${(Math.random() * 1000000).toFixed(0)}${moment().format('YYYYMMDDHHmmss')}`,
        receivetime: this.receivetime
      }).then(res => {
        if (res.code == '200') {
          this.$refs.uToast.show({
            title: '下单成功，请前往个人中心查看！',
            type: 'success',
          })
          // 删除购物车
          for (let cart of this.cartList.filter(v => v.check)) {
            deleteCart(cart.id).then(res => {
              console.log(res)
            })
          }
          setTimeout(() => {
            success: () => {
              this.$u.route('/pages/user/center')
              uni.switchTab({ url: `/pages/user/center` });
            }
          }, 1000)
        } else {
          this.$refs.uToast.show({
            title: res.msg,
            type: 'error',
          })
        }
      })
    },
    clearCart() {
      console.log(this.cartList)
      for (let cart of this.cartList) {
        deleteCart(cart.id).then(res => {

        })
      }
      this.cartList = []
    },
    articleDetail(row) {
      this.$u.route("/pages/good/articleDetail", {
        article: row.goodsId,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f7f7f7;
  min-height: 100vh;
}
.cart-scroll {
  height: calc(100% - 160rpx);
  overflow-y: scroll;
  overflow: hidden;
}

.item {
  display: flex;
  padding: 20rpx;
}

image {
  width: 120rpx;
  flex: 0 0 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
}

.title {
  text-align: left;
  font-size: 28rpx;
  color: $u-content-color;
  margin-top: 20rpx;
}
.pay {
  width: 100%;
  position: fixed;
  bottom: 0;
  height: 120rpx;
  padding: 12rpx 20rpx;
  display: flex;
  justify-content: space-between;
  background: #fff;
  align-items: center;
}
.container {
  background-color: #f7f7f7;
  min-height: calc(100% - 120rpx);
  overflow: hidden;
}
.number {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
}
.btn {
  padding: 8rpx 20rpx;
  color: #fff;
  background: red;
  border-radius: 30rpx;
  margin-left: 30rpx;
}
.people {
  padding: 30rpx;
  background: #fff;
  width: calc(100% - 60rpx);
  margin: auto;
  border-radius: 20rpx;
  .img {
    width: 30rpx;
    height: 30rpx;
  }

  .each {
    padding: 20rpx 0 20rpx 30rpx;
    border-bottom: 1rpx solid #e4dada;
    position: relative;
    .head {
      display: flex;
      width: 100%;
      justify-content: space-between;
      font-weight: bold;
    }
    .cardno {
      margin-top: 10rpx;
    }
  }

  .eachChoose {
    background: cyan;
  }

  .add {
    text-align: center;
    margin-top: 30rpx;
    width: 100%;
    font-weight: bold;
  }

  .check {
    position: absolute;
    left: -30rpx;
    top: 30rpx;
  }
}
.btn2 {
  padding: 12rpx 20rpx;
  color: #fff;
  background: red;
  border-radius: 30rpx;
  margin-left: 30rpx;
  text-align: center;
  margin-top: 20rpx;
}
.red {
  margin-left: 20rpx;
  color: red;
}
</style>
